<?php
/**
 * @return false|mysqli|null
 * 连接数据库
 */
function mConn()
{
    static $conn = null;
    if ($conn === null) {
        $conf = require 'config.php';
        $conn = mysqli_connect($conf['host'], $conf['user'], $conf['password'], $conf['database']);
        if (mysqli_connect_errno($conn)) {
            echo mysqli_connect_errno() . ':' . mysqli_connect_error();
            exit();
        }
    }
    return $conn;
}

/**
 * @param $sql
 * @return bool|mysqli_result
 * 发送sql语句
 */
function mQuery($sql)
{
    $conn = mConn();
    $res = mysqli_query($conn, $sql);
    if ($res){
        mLog($sql);
    }else{
        mLog($sql."\n".mysqli_error($conn));
    }
    return $res;
}

function mLog($sql){
    $path=ROOT.'/log/'.date('Ymd').'.txt';
    $header="-------------------------------\n".date('Ymd H:i:s')."\n";
    file_put_contents($path,$header.$sql."\n",FILE_APPEND);
}

/**
 * @param $sql
 * @return array
 * 获取所有行
 */
function mGetAll($sql)
{
    $res = mQuery($sql);
    if ($res) {
        $data = [];
        while ($row = mysqli_fetch_assoc($res)) {
            $data[] = $row;
        }
        return $data;
    } else {
        return false;
    }
}

/**
 * @param $sql
 * @return array|null
 * 获取一行
 */
function mGetRow($sql)
{
    $res = mQuery($sql);
    return $res ? mysqli_fetch_assoc($res) : false;
}

/**
 * @param $sql
 * @return mixed
 * 获取一列
 */
function mGetOne($sql)
{
    $res = mQuery($sql);
    return $res ? mysqli_fetch_row($res)[0] : false;
}

/**
 * @param $table
 * @param $data
 * @param string $act
 * @param string $where
 * @return bool|mysqli_result
 */
function mExec($table, $data, $act = 'insert', $where = '0')
{
    if ($act == 'insert') {
        //insert into cat(cat_id,cat_name) values('123','123');
        $sql = "insert into $table (";
        $sql .= implode(',', array_keys($data)) . ") values('";
        $sql .= implode("','", array_values($data)) . "');";
//        echo $sql;
        return mQuery($sql);
    } else {
        $sql = "update $table set ";
        foreach ($data as $k => $v) {
            $sql .= $k . "='" . $v . "',";
        }
        $sql = rtrim($sql, ',');
        $sql .= ' where ' . $where;
        mQuery($sql);
        if(mysqli_affected_rows(mConn())>0){
            return true;
        }else{
            return false;
        }
    }
}
